package com.minelx.datamicroscope.querylanguage.data.sql;

import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.expr.SQLAggregateExpr;
import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr;
import com.alibaba.druid.sql.ast.statement.SQLSelectItem;
import com.minelx.datamicroscope.querylanguage.data.CollectingField;
import com.minelx.datamicroscope.querylanguage.data.CollectingKey;

import java.util.Map;

public class TableAliasedSelectItem {

	private final SelectItem selectItem;

	private final String tableAlias;

	private TableAliasedSelectItem(String tableAlias, SelectItem selectItem) {
		this.tableAlias = tableAlias;
		this.selectItem = selectItem;
	}

	public SelectItem getSelectItem() {
		return selectItem;
	}

	public String getTableAlias() {
		return tableAlias;
	}

	public static TableAliasedSelectItem create(String tableAlias, SelectItem selectItem) {
		return new TableAliasedSelectItem(tableAlias, selectItem);
	}

	static TableAliasedSelectItem from(SQLSelectItem sqlSelectItem, Map<String, CollectingKey> aliasedTables) {
		SQLPropertyExpr result = getSqlPropertyExpr(sqlSelectItem.getExpr());
		String tableAlias = result.getOwner().toString();
		SelectItem selectItem = new SelectItem(aliasedTables.get(tableAlias), CollectingField.of(sqlSelectItem));
		return create(tableAlias, selectItem);
	}

	private static SQLPropertyExpr getSqlPropertyExpr(SQLExpr expr) {
		if (expr instanceof SQLPropertyExpr) {
			return (SQLPropertyExpr) expr;
		} else if (expr instanceof SQLAggregateExpr) {
			SQLAggregateExpr sqlAggregateExpr = (SQLAggregateExpr) expr;
			return ((SQLPropertyExpr) sqlAggregateExpr.getArguments().get(0));
		} else {
			throw new UnsupportedOperationException("TableAliasedSelectItem.from is not supported.");
		}
	}

	@Override
	public String toString() {
		return "TableAliasedSelectItem{" +
				"selectItem=" + selectItem +
				", tableAlias='" + tableAlias + '\'' +
				'}';
	}
}
